package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.GradePositionRequest;
import com.xmy.cultivate.feign.english.IFeiEnglishFeignClient;
import com.xmy.cultivate.mapper.StudentClassTypeMapper;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hpiggy
 * @since 2023-09-04
 */
@Service
public class StudentClassTypeServiceImpl extends ServiceImpl<StudentClassTypeMapper, StudentClassType> implements IStudentClassTypeService {

    @Autowired
    StudentClassTypeMapper studentClassTypeMapper;

    @Autowired
    IQuarterService iQuarterService;

    @Autowired
    IDictService iDictService;

    @Autowired
    IOrderDetailService iOrderDetailService;

    @Autowired
    IFeiEnglishFeignClient iFeiEnglishFeignClient;

    @Autowired
    IStudentGradeService iStudentGradeService;

    @Autowired
    IGradeService iGradeService;

    @Autowired
    ITranscriptService iTranscriptService;

    @Autowired
    ICourseTypeService iCourseTypeService;

    public StudentClassType getOneForYearPart(Integer yearPart,Integer quarterNum,Long subjectsId,Long studentId){
        return studentClassTypeMapper.getOneForYearPart(yearPart,quarterNum,subjectsId,studentId);
    }

    /**
     * 获取分班班型
     * @param yearPart
     * @param quarterNum
     * @param subjectsId
     * @param studentId
     * @param yearClassId
     * @return
     */
    @Override
    public StudentClassType getAutoDivideClassType(Integer yearPart, Integer quarterNum, Long subjectsId, Long studentId, Integer yearClassId){
        StudentClassType studentClassType = null;
        Long classTypeId = 1575859909042028546L;//默认提高班
        String classTypeIdStr = "1575859909042028546";
        Long classTypeIdNow = classTypeId;
        Integer toType =1;//要获取的班型类型，由于现在没有预备班，所以都为1

        if (subjectsId.equals(1L) && (yearClassId < 3 || (yearClassId == 3 && (quarterNum.equals(3) || quarterNum.equals(4))))){
            studentClassType = new StudentClassType();
            studentClassType.setYearPart(yearPart);
            studentClassType.setQuarterNum(quarterNum);
            studentClassType.setStudentId(studentId);
            studentClassType.setSubjectsId(subjectsId);
            studentClassType.setYearClassId(yearClassId);
            studentClassType.setClassTypeId(classTypeId);//默认提高班
        }else if (subjectsId.equals(3L) && (yearClassId < 8 || (yearClassId == 8 && (quarterNum.equals(3) || quarterNum.equals(4))))){
            Quarter quarterLast = iQuarterService.getLastForTranscription(yearPart,quarterNum);
            //物理初二暑假与秋季用上一学期数据的分数计算
            Integer examNum = 3;//期末的
            Transcript transcript = iTranscriptService.getDataTranscript(quarterLast.getYearPart(),quarterLast.getNum(),studentId,2L,examNum);
            if (transcript!=null && transcript.getIsStatistics().equals(1)){
                BigDecimal diffScorse = null;
                String diffScorseStr = null;//分段对比值
                String score = transcript.getScore();
                if (transcript.getScoreType().equals(1)){
                    diffScorse = new BigDecimal(90);
                    BigDecimal bScorese = new BigDecimal(score);
                    if (bScorese.compareTo(diffScorse) >= 0) {
                        //学期
                        CourseType courseType = iCourseTypeService.getNextCourseType(classTypeId, toType);
                        if (courseType != null) {
                            classTypeIdStr += "," + courseType.getId();
                            classTypeIdNow = courseType.getId();
                        }
                    }
                }else {
                    diffScorseStr = "A,A+";
                    if (diffScorseStr != null) {
                        List<String> diffScorseList = Arrays.asList(diffScorseStr.split(","));
                        if (diffScorseList.contains(score)) {
                            //学期
                            CourseType courseType = iCourseTypeService.getNextCourseType(classTypeId, toType);
                            if (courseType != null) {
                                classTypeIdStr += "," + courseType.getId();
                                classTypeIdNow = courseType.getId();
                            }
                        }
                    }
                }
                studentClassType = new StudentClassType();
                studentClassType.setYearPart(yearPart);
                studentClassType.setQuarterNum(quarterNum);
                studentClassType.setYearClassId(yearClassId);
                studentClassType.setClassTypeId(classTypeIdNow);
                studentClassType.setClassTypeIdStr(classTypeIdStr);
                studentClassType.setStudentId(studentId);
                studentClassType.setSubjectsId(subjectsId);//
            }
        }else {
            studentClassType = studentClassTypeMapper.getOneForYearPart(yearPart,quarterNum,subjectsId,studentId);
        }
        return studentClassType;
    }

    /**
     * 获取分班班型或者分数
     * @param yearPart
     * @param quarterNum
     * @param subjectsId
     * @param studentId
     * @param yearClassId
     * @return
     */
    @Override
    public GradePositionRequest getAutoDivideClassTypeOrScore(Integer yearPart, Integer quarterNum, Long subjectsId, Long studentId, Integer yearClassId){
        Long classTypeId = 1575859909042028546L;//默认提高班
        GradePositionRequest gradePositionRequest = new GradePositionRequest();
        gradePositionRequest.setIsHasData(0);
        gradePositionRequest.setScore(new BigDecimal(0));

        if (yearClassId<=1 && (quarterNum==3 || quarterNum==4)){
            gradePositionRequest.setType(2);
            gradePositionRequest.setClassTypeId(classTypeId);
            gradePositionRequest.setIsHasData(1);
        }else {
            if (subjectsId.equals(1L) && (yearClassId < 3 || (yearClassId == 3 && (quarterNum.equals(3) || quarterNum.equals(4))))){
                gradePositionRequest.setType(2);
                gradePositionRequest.setClassTypeId(classTypeId);
                gradePositionRequest.setIsHasData(1);
            }else if (subjectsId.equals(3L) && (yearClassId < 8 || (yearClassId == 8 && (quarterNum.equals(3) || quarterNum.equals(4))))){
                Quarter quarterLast = iQuarterService.getLastForTranscription(yearPart,quarterNum);
                //物理初二暑假与秋季用上一学期数据的分数计算
                Integer examNum = 3;//期末的
                Transcript transcript = iTranscriptService.getDataTranscript(quarterLast.getYearPart(),quarterLast.getNum(),studentId,2L,examNum);
                if (transcript!=null && transcript.getIsStatistics().equals(1)){
                    gradePositionRequest.setScore(transcript.getScoreEnd());
                    gradePositionRequest.setType(1);
                    gradePositionRequest.setIsHasData(1);
                }
            }else {
                Quarter quarterLast = iQuarterService.getLastForTranscription(yearPart,quarterNum);
                //物理初二暑假与秋季用上一学期数据的分数计算
                Integer examNum = 1;//期中
                //当前学期期中
                Transcript transcript = iTranscriptService.getDataTranscript(yearPart,quarterNum,studentId,subjectsId,examNum);
                if (transcript!=null && transcript.getIsStatistics().equals(1)){
                    gradePositionRequest.setScore(transcript.getScoreEnd());
                    gradePositionRequest.setType(1);
                    gradePositionRequest.setIsHasData(1);
                }else {
                    examNum = 3;
                    transcript = iTranscriptService.getDataTranscript(quarterLast.getYearPart(),quarterLast.getNum(),studentId,subjectsId,examNum);
                    if (transcript!=null && transcript.getIsStatistics().equals(1)){
                        gradePositionRequest.setScore(transcript.getScoreEnd());
                        gradePositionRequest.setType(1);
                        gradePositionRequest.setIsHasData(1);
                    }
                }
            }
        }
        return gradePositionRequest;
    }



    public void updateClassType(){
        Quarter quarter = iQuarterService.getNowQuarter();
        //获取上一个学期
        Quarter lastQuarter = iQuarterService.getLastQuarter(quarter.getYearPart(),quarter.getNum());
        Dict dict = iDictService.getQuarter(lastQuarter.getNum());
        //dict.getTag();//1为假期，0为非假期
        List<OrderDetail> orderDetailList = iOrderDetailService.getOrderDetailForResidueCoruseCount();
        for (OrderDetail orderDetail:orderDetailList){
            try{
                if (orderDetail.getSubjectsId().equals(1L)){
                    this.updateClassTypeEnglish(orderDetail,dict,quarter,lastQuarter);
                }else if (orderDetail.getSubjectsId().equals(2L)){
                    this.updateClassTypeOther(orderDetail,dict,quarter,lastQuarter);
                }else if (orderDetail.getSubjectsId().equals(3L)){
                    this.updateClassTypeOther(orderDetail,dict,quarter,lastQuarter);
                }
            }catch (Exception e){
            }
        }
    }

    /**
     * 英语
     * @param orderDetail
     * @param dict
     * @param quarter
     * @param lastQuarter
     */
    public void  updateClassTypeEnglish(OrderDetail orderDetail,Dict dict,Quarter quarter,Quarter lastQuarter){

        Integer isVacation = dict.getTag();//上个学期是否假期

        //调用学期系统数据
        Map<String,String> map =  iFeiEnglishFeignClient.getStudentClassType(orderDetail.getStudentId(),isVacation,lastQuarter.getYearPart(),lastQuarter.getNum());

        QueryWrapper<StudentClassType> studentClassTypeQueryWrapper = new QueryWrapper<>();
        studentClassTypeQueryWrapper.eq("student_id",orderDetail.getStudentId());
        studentClassTypeQueryWrapper.eq("subjects_id",orderDetail.getSubjectsId());
        studentClassTypeQueryWrapper.eq("year_part",quarter.getYearPart());
        studentClassTypeQueryWrapper.eq("quarter_num",quarter.getNum());

        //是否已经添加过
        StudentClassType studentClassType = this.getOne(studentClassTypeQueryWrapper);
        if (studentClassType == null){
            studentClassType = new StudentClassType();
            //iStudentClassTypeService.save(studentClassType);
        }
        studentClassType.setYearPart(quarter.getYearPart());
        studentClassType.setQuarterNum(quarter.getNum());
        studentClassType.setStudentId(orderDetail.getStudentId());
        studentClassType.setSubjectsId(orderDetail.getSubjectsId());
        studentClassType.setYearClassId(orderDetail.getYearClassId());
        studentClassType.setLastClassTypeId(0L);
        studentClassType.setRemark("");

        if(StringUtils.isNotBlank(map.get("classTypeId")) && StringUtils.isNotBlank(map.get("classTypeIdStr"))){
            Long classTypeId = Long.parseLong(map.get("classTypeId"));
            String classTypeIdStr = map.get("classTypeIdStr");
            studentClassType.setClassTypeId(classTypeId);
            studentClassType.setClassTypeIdStr(classTypeIdStr);
        }else {

            Integer yearPart = 2023;
            Integer quarterNum = 2;
            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.eq("year_part",yearPart);
            studentGradeQueryWrapper.eq("quarter_num",quarterNum);
            studentGradeQueryWrapper.ne("status",3);
            studentGradeQueryWrapper.eq("student_id",orderDetail.getStudentId());
            studentGradeQueryWrapper.orderByDesc("id");
            studentGradeQueryWrapper.last("limit 1");
            StudentGrade studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
            if (studentGrade!=null){
                //临时设置，春季班上课的班型
                Grade grade = iGradeService.getById(studentGrade.getGradeId());
                if (grade !=null){
                    if (grade.getCourseTypeId().equals(1570701121454350337L)){
                        studentClassType.setClassTypeId(1565023758494502914L);
                        studentClassType.setClassTypeIdStr("1565023758494502914");
                    }else {
                        studentClassType.setClassTypeId(grade.getCourseTypeId());
                        studentClassType.setClassTypeIdStr(grade.getCourseTypeId().toString());
                    }
                }
            }else {
                //没有数据，为新生
                studentClassType.setClassTypeId(1575859909042028546L);
                studentClassType.setClassTypeIdStr("1575859909042028546");
            }

            //iStudentClassTypeService.save(studentClassType);
            //this.updateClassTypeOther(orderDetail,dict,quarter,lastQuarter);
        }

        this.saveOrUpdate(studentClassType);
    }


    /**
     * 英语、数学、物理
     * @param orderDetail
     * @param dict
     * @param quarter
     * @param lastQuarter
     */
    public void  updateClassTypeOther(OrderDetail orderDetail,Dict dict,Quarter quarter,Quarter lastQuarter){
        //1为假期（上个学期为假期）
        if (dict.getTag().equals(1)){
            //如果上个学期为假期，再获取出上个学期
            lastQuarter = iQuarterService.getLastQuarter(lastQuarter.getYearPart(),lastQuarter.getNum());
        }
        QueryWrapper<Transcript> transcriptQueryWrapper = new QueryWrapper<>();
        transcriptQueryWrapper.eq("year_part",lastQuarter.getYearPart());
        transcriptQueryWrapper.eq("quarter_num",lastQuarter.getNum());
        transcriptQueryWrapper.eq("subjects_id",orderDetail.getSubjectsId());
        transcriptQueryWrapper.eq("student_id",orderDetail.getStudentId());
        transcriptQueryWrapper.eq("is_statistics",1);
        transcriptQueryWrapper.last("limit 1");
        Transcript transcript = iTranscriptService.getOne(transcriptQueryWrapper);
        Long classTypeId = 1575859909042028546L;//默认提高班
        String classTypeIdStr = "1575859909042028546";
        boolean isAt = false;

        if (transcript != null){
            isAt = true;

            BigDecimal diffScorse = null;
            String diffScorseStr = null;//分段对比值
            CourseType courseType = null;
            Integer yearClassId = orderDetail.getYearClassId();
            String score = transcript.getScore();

            //英语
            if (transcript.getSubjectsId().equals(1L)){
                if (transcript.getGradeSection().equals(0)){
                }else if (transcript.getGradeSection().equals(1)){
                    //分数类型：1分数，2分段
                    if (transcript.getScoreType().equals(1)){
                        diffScorse = new BigDecimal(90);
                    }else {
                        diffScorseStr = "A,A+";
                    }
                }else if (transcript.getGradeSection().equals(2)){
                    //分数类型：1分数，2分段
                    if (transcript.getScoreType().equals(1)){
                        diffScorse = new BigDecimal(90);
                    }else {
                        diffScorseStr = "A,A+";
                    }
                }else if (transcript.getGradeSection().equals(3)){
                    //分数类型：1分数，2分段
                    //高一秋季班统一为提高班
                    if (quarter.getNum().equals(4)&& yearClassId.equals(10)){

                    }else {
                        if (transcript.getScoreType().equals(1)){
                            diffScorse = new BigDecimal(90);
                        }else {
                            diffScorseStr = "A,A+";
                        }
                    }
                }
            }else  if (transcript.getSubjectsId().equals(2L)){
                //数学
                if (transcript.getGradeSection().equals(0)){

                }else if (transcript.getGradeSection().equals(1)){
                    //分数类型：1分数，2分段
                    if (transcript.getScoreType().equals(1)){
                        diffScorse = new BigDecimal(80);
                    }else {
                        diffScorseStr = "A,A+";
                    }
                }else if (transcript.getGradeSection().equals(2)){
                    //分数类型：1分数，2分段
                    if (transcript.getScoreType().equals(1)){
                        diffScorse = new BigDecimal(90);
                    }else {
                        diffScorseStr = "A,A+";
                    }
                }else if (transcript.getGradeSection().equals(3)){
                    //分数类型：1分数，2分段
                    //秋季班高一
                    if (quarter.getNum().equals(4) && yearClassId.equals(10)){
                    }else {
                        if (transcript.getScoreType().equals(1)){
                            diffScorse = new BigDecimal(70);
                        }else {
                            diffScorseStr = "A,A+";
                        }
                    }
                }
            }else  if (transcript.getSubjectsId().equals(3L)){
                if (transcript.getGradeSection().equals(2)){
                    if (transcript.getScoreType().equals(1)){
                        //初二秋季班第一学期
                        if (quarter.getNum().equals(4) && yearClassId.equals(8)){
                            diffScorse = new BigDecimal(84);
                        }else {
                            diffScorse = new BigDecimal(80);
                        }
                    }
                }else if (transcript.getGradeSection().equals(3)){
                    //分数类型：1分数，2分段
                    //秋季班统一为提高班
                    if (quarter.getNum().equals(4) && yearClassId.equals(10)){

                    }else {
                        if (transcript.getScoreType().equals(1)){
                            diffScorse = new BigDecimal(70);
                        }
                    }
                }
            }
            if (transcript.getScoreType().equals(1)){
                if (diffScorse !=null){

                    BigDecimal bScorese = new BigDecimal(score);
                    if (bScorese.compareTo(diffScorse)>=0){
                        //学期
                        courseType = iCourseTypeService.getNextCourseType(classTypeId,quarter.getType());
                        if (courseType!= null){
                            classTypeIdStr+=","+classTypeId;
                        }
                    }
                }
            }else {
                if (diffScorseStr != null){
                    List<String> diffScorseList = Arrays.asList(diffScorseStr.split(","));
                    if (diffScorseList.contains(score)){
                        //学期
                        courseType = iCourseTypeService.getNextCourseType(classTypeId,quarter.getType());
                        if (courseType!= null){
                            classTypeIdStr+=","+classTypeId;
                        }
                    }
                }
            }
        }

        if (isAt){
            QueryWrapper<StudentClassType> studentClassTypeQueryWrapper = new QueryWrapper<>();
            studentClassTypeQueryWrapper.eq("student_id",orderDetail.getStudentId());
            studentClassTypeQueryWrapper.eq("subjects_id",orderDetail.getSubjectsId());
            studentClassTypeQueryWrapper.eq("year_part",quarter.getYearPart());
            studentClassTypeQueryWrapper.eq("quarter_num",quarter.getNum());

            //是否已经添加过
            StudentClassType studentClassType = this.getOne(studentClassTypeQueryWrapper);

            if (studentClassType == null){
                studentClassType = new StudentClassType();
            }

            studentClassType.setYearPart(quarter.getYearPart());
            studentClassType.setQuarterNum(quarter.getNum());
            studentClassType.setStudentId(orderDetail.getStudentId());
            studentClassType.setSubjectsId(orderDetail.getSubjectsId());
            studentClassType.setClassTypeId(classTypeId);
            studentClassType.setClassTypeIdStr(classTypeIdStr);
            studentClassType.setLastClassTypeId(0L);
            studentClassType.setRemark("");
            this.saveOrUpdate(studentClassType);
        }
    }
}
